package com.gitee.melin.bee.core.enums.mvc;

import com.gitee.melin.bee.core.enums.BaseStringEnum;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

/** Created by libinsong on 2020/9/9 9:41 下午 */
public class StringToEnumConverter<T extends BaseStringEnum> implements Converter<String, T> {

    private final Map<String, T> enumMap = new HashMap<>();

    public StringToEnumConverter(Class<T> enumType) {
        T[] enums = enumType.getEnumConstants();
        for (T e : enums) {
            String enumName = StringUtils.lowerCase(e.getValue());
            enumMap.put(enumName, e);
        }
    }

    @Override
    public T convert(String source) {
        String lowerSource = StringUtils.lowerCase(source);
        T t = enumMap.get(lowerSource);
        if (t == null) {
            throw new IllegalArgumentException(
                    "无法匹配对应的枚举类型: " + lowerSource + ", enums: " + StringUtils.join(enumMap.keySet(), ", "));
        }
        return t;
    }
}
